<template>
  <Dialog class="system-form-disabled" :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">

      <el-form-item label="上级菜单" prop="parentMenuId">
        <el-tree-select
        v-model="formData.parentMenuId" 
        :data="menus" :props="menuTreeProps" check-strictly
          node-key="id" placeholder="请选择系统菜单" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FormConstructApi, FormConstructVO } from '@/api/infra/formconstruct/index'
import * as MenuApi from '@/api/system/menu'
import { handleTree } from '@/utils/tree'
/** 表单构建 表单 */
defineOptions({ name: 'FormConstructForm' })
const message = useMessage() // 消息弹窗
const menus = ref<any[]>([])
const menuTreeProps = {
  label: 'name'
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('构建') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  parentMenuId: undefined
})
const formRef = ref() // 表单 Ref
const formRules = reactive({
  parentMenuId: [
    { required: true, message: '上级菜单不能为空', trigger: 'blur' },
    { validator: validatemMenu, trigger: 'blur' }
  ],

})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FormConstructApi.getFormConstruct(id)
    } finally {
      formLoading.value = false
    }
  }
}
const emit = defineEmits(['buildSuccess']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    const data: any = formData.value as unknown as FormConstructVO
    const params: any = {
      id: data.id,
      parentMenuId: data.parentMenuId
    }
    await FormConstructApi.buildConstruct(params)
    message.success('构建成功')
    emit('buildSuccess')
    dialogVisible.value = false
    // 发送操作成功的事件
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
onMounted(async () => {
  try {
    // 加载菜单
    const resp = await MenuApi.getSimpleMenusList()
    menus.value = [{
      id: 0,
      children: handleTree(resp),
      name: '根目录',
      parentId: 0,
      type: 1
    }]
  } catch { }
})
/** 重置表单 */
const resetForm = () => {
  Object.keys(formData.value).forEach((key) => {
    formData.value[key] = undefined
  })
  formRef.value?.resetFields()
}
function validatemMenu(rule, value, callback) {
  console.log(value, 'value')
  if (value === 0) {
    return callback()
  }
  if (!value) {
    return callback(new Error('上级菜单不能为空'))
  }
  return callback()
}


</script>